package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	unsafeWrite()
	safeWrite()
	time.Sleep(time.Second)
}

func unsafeWrite() {
	conflictMap := make(map[int]int)
	for i := 0; i < 100; i++ {
		go func() { conflictMap[i] = i }()
	}
}

type SafeMap struct {
	m map[int]int
	*sync.Mutex
}

func safeWrite() {
	safeMap := SafeMap{m: make(map[int]int), Mutex: &sync.Mutex{}}
	for i := 0; i < 100; i++ {
		go func() { safeMap.put(i, i) }()
	}

	for i := 0; i < 100; i++ {
		// 会有很多0， 因为在get的时候还没put
		go func() { fmt.Println(safeMap.get(i)) }()
	}
}

func (s *SafeMap) put(k, v int) {
	s.Lock()
	defer s.Unlock()
	s.m[k] = v
}

func (s *SafeMap) get(k int) int {
	s.Lock()
	defer s.Unlock()
	return s.m[k]
}
